<?php
//**---------------------------------------------------------------------+
//** 服务层文件 -- APP版本管理
//**---------------------------------------------------------------------+
//** 版权所有：江西佰商科技有限公司. 官网：https://www.tigshop.com
//**---------------------------------------------------------------------+
//** 作者：Tigshop团队，yq@tigshop.com
//**---------------------------------------------------------------------+
//** 提示：Tigshop商城系统为非免费商用系统，未经授权，严禁使用、修改、发布
//**---------------------------------------------------------------------+

namespace app\service\admin\setting;

use app\model\setting\Config;
use app\service\common\BaseService;
use exceptions\ApiException;

/**
 * 授权管理服务类
 */
class LicensedService extends BaseService
{

    public function __construct()
    {
    }

    /**
     * 获取详情
     * @return Config|null
     * @throws ApiException
     */
    public function getDetail(): Config|null
    {
        $result = Config::where('code', "auto_generate_licensed_data")->find();
        return $result;
    }

    /**
     * 更新授权
     * @return true
     */
    public function update(string $licensed)
    {
        $iv = 'tigshop123456789';
        $license = @openssl_decrypt($licensed, 'AES-256-CBC', '', 0, $iv);
        $license = @json_decode(base64_decode($license), true);
        if (!$license || !is_array($license)) {
            throw new ApiException("授权码错误");
        }
        if (strtotime($license['expirationTime']) < time()) {
            throw new ApiException("授权码已过期");
        }
        $result = Config::where('code', "auto_generate_licensed_data")->find();
        $license['license'] = $licensed;
        if ($result) {
            $result->data = $license;
            $result->save();
        } else {
            Config::create([
                'code' => "auto_generate_licensed_data",
                'data' => $license,
            ]);
        }
        return true;
    }

}
